package com.mzm.dao;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Repository;

import com.mzm.PathUtils;
import com.mzm.api.CategoryDto;
import com.mzm.domain.Category;
import com.mzm.service.DtoConversions;
import com.mzm.util.persistency.GenericJpaDaoImpl;
import com.mzm.util.persistency.JpqlQueryBuilder;

@Repository("categoryDao")
public class CategoryDao extends GenericJpaDaoImpl<Category, Integer>{

	public CategoryDao() {
		super(Category.class);
	}
	
	public Category getCategory(String path){
		List<Category> matchingNodes = getJpaTemplate().find(
				"SELECT " +
				"	c " +
				"FROM " +
				"	com.mzm.domain.Category c " +
				"WHERE " +
				"	c.path=?1",
				path);
		if(matchingNodes.isEmpty()){
			return null;
		}
		if(matchingNodes.size() > 1){
			throw new IllegalStateException("More than one nodes correspond to the path: "+path);
		}
		Category node = (Category) matchingNodes.get(0);
		return node;
	}
	
	public CategoryDto getCategoryTree(final String rootPath){
		JpqlQueryBuilder qb = new JpqlQueryBuilder(getJpaTemplate());
		qb.select("c");
		qb.from("com.mzm.domain.Category c");
		if(rootPath != null){
			qb.where("c.path like ?", rootPath+"%");
		}
		qb.orderBy("c.path");
		Map<String, CategoryDto> path2cat = new HashMap<String, CategoryDto>();
		List<Category> l = qb.find();
		for (Category cat : l) {
			CategoryDto dto = DtoConversions.convert(cat);
			path2cat.put(cat.getPath(), dto);
			if(PathUtils.isSubpathOf(rootPath, cat.getPath())){
				String parentPath = PathUtils.getParentPath(cat.getPath());
				CategoryDto parent = path2cat.get(parentPath);
				if(parent == null){
					System.err.println("parent of "+cat.getPath()+" was not found");
				}
				else {
					parent.addChild(dto);
				}
			}
		}
		return path2cat.get(rootPath);
	}
}
